'''
Created on 2011-10-26

@author: tony.li.fly@gmail.com
'''
from django.http import HttpResponseRedirect 
from django.core.serializers import serialize
from django.utils.simplejson import dumps, loads, JSONEncoder
from decimal import Decimal
from datetime import datetime,date
from django.db.models.query import QuerySet
from django.db.models import Model
class AuthorityMiddleware(object):
    
    def process_request(self, request):
        if request.path.startswith("/static") or request.path.startswith("/login"):
            pass
        else:
            if request.session.get('user',False):
                pass
            else :
                return HttpResponseRedirect("/static/index.html")  


class Encoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return "%s" % o 
        elif isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, QuerySet):
            return loads(serialize('json', o))
        elif isinstance(o, Model):
            set_obj = [o]
            set_obj = loads(serialize('json', set_obj))
            return set_obj[0]
        return super(Encoder, self).default(o)